import axios from 'axios'
import { Message, Loading, MessageBox } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

let loading // 定义loading变量
function startLoading() { // 使用Element loading-start 方法
  loading = Loading.service({
    lock: true,
    text: '加载中……',
    background: 'rgba(0, 0, 0, 0.7)'
  })
}
function endLoading() { // 使用Element loading-close 方法
  loading.close()
}
let needLoadingRequestCount = 0
export function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading()
  }
  needLoadingRequestCount++
}

export function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    endLoading()
  }
}

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 500000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['Authorization'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = getToken()
    }
    showFullScreenLoading()
    return config
  },
  error => {
    // do something with request error
    // console.log(error) // for debug
    tryHideFullScreenLoading()
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    if (Object.prototype.toString.call(response.data).includes('Blob')) {
      // 如果是下载
      return response
    }
    const res = response.data
    if (res.code !== 0) {
      Message({
        message: res.msg || '未知错误',
        type: 'error',
        duration: 5 * 1000
      })
      if (res.code === 90001) {
        // to re-login
        MessageBox.confirm('您的登录已经失效，请重新登录', '重新登录', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      tryHideFullScreenLoading()
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      tryHideFullScreenLoading()
      return res
    }
  },
  error => {
    tryHideFullScreenLoading()
    return Promise.reject(error.message)
  }
)

export default service
